using System;
using System.Data;
using System.Data.SqlClient;
using CoreLibrary.Sql;

namespace CoreLibrary.Messaging.Sql {

    public class UpdateMessageStatus : ISqlUpdator<bool> {

        private readonly string _tableName;
        private readonly string _messageId;
        private readonly MessageStatus _newStatus;
        private readonly string _fault;
        private readonly int _retry;
        private readonly DateTime _dateScheduled;

        public UpdateMessageStatus(string tableName, string messageId, MessageStatus newNewStatus, string fault, int retry, DateTime dateScheduled) {
            _tableName = tableName;
            _messageId = messageId;
            _newStatus = newNewStatus;
            _fault = fault;
            _retry = retry;
            _dateScheduled = dateScheduled;
        }

        public string GetSQL() {
            return string.Format(@"
                update {0}
                set status = @newStatus, 
                    fault  = @fault,
                    retry  = @retry,
                    date_scheduled = @dateScheduled
                where id = @id
            ", _tableName);
        }

        public void SetParameters(SqlCommand command) {
            SqlParameterCollection parameters = command.Parameters;
            parameters.Add("@id",        SqlDbType.UniqueIdentifier).Value = new Guid(_messageId);
            parameters.Add("@newStatus", SqlDbType.Int).Value = (int) _newStatus;
            parameters.Add("@fault",     SqlDbType.VarChar).Value = Util.GetString(_fault);
            parameters.Add("@retry",     SqlDbType.Int).Value = _retry;
            parameters.Add("@dateScheduled", SqlDbType.DateTime).Value = _dateScheduled;
        }

        public bool GetResult(SqlConnection conn, int result) {
            return result > 0;
        }
    }
}